package com.celebracion.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class FileUtil {
	//Funciones Auxiliares
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    
    public static final String DIRECTORIO_APP_TEMP="MyAppCelebracionTemp";
    public static final String DIRECTORIO_APP_SAVED="MyAppCelebracionSaved";
    /** Create a File for saving an image or video */
   
    private static HashMap<String,String> getNameForFile(int type, long idCelebracion, String persistenceType){
    	
    	HashMap<String,String> result=new HashMap<String,String>();
    	String path="";
    	
    	
    	String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        
        if (type == MEDIA_TYPE_IMAGE){
            path+= "IMG_"+ timeStamp + ".jpg";
        } else if(type == MEDIA_TYPE_VIDEO) {
            //mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_"+ timeStamp + ".mp4"); 
        	path+= "VID_"+ timeStamp + ".3gp"; 
        } else {
            return null;
        }
        result.put("path",path);
        result.put("persistenceType", persistenceType);
        result.put("idCelebracion",idCelebracion+"");
        result.put("fullPath", idCelebracion+File.separator+persistenceType+File.separator+path);
        return result;
    }
    
    public static File getInternalFile(int type, long idCelebracion, String persistenceType, Context ctx){
    	HashMap<String,String> paths=getNameForFile(type,idCelebracion,persistenceType);
    	
    	
     //	File dirApp=ctx.getDir(paths.get("idCelebracion"), Context.MODE_WORLD_READABLE);
    	
    	File dirGeneral= new File(Environment.getExternalStoragePublicDirectory(
    	        Environment.DIRECTORY_PICTURES), DIRECTORIO_APP_SAVED);
    	if(!dirGeneral.exists())
    		dirGeneral.mkdir();
    	
     	 File dirApp = new File(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES), DIRECTORIO_APP_SAVED + File.separator + paths.get("idCelebracion"));
     	if(!dirApp.exists())
       		dirApp.mkdir();
    	
  
       	//se crea el directorio de temporales y de definitivos
       	File dirTemp=new File(dirApp.toString()+File.separator+DIRECTORIO_APP_TEMP);
       	if(!dirTemp.exists()){
       		dirTemp.mkdir();
       		try {
    			//Se le dan permisos 777 al fichero para que lo pueda ejecutar el videoView ya que usa un componente externo
    			Runtime.getRuntime().exec("chmod 777 "+dirTemp.toString());
    		} catch (IOException e) {
    			
    			e.printStackTrace();
    		}
       	}
       	
		File filePersistence=new File(dirApp.toString()+File.separator+paths.get("persistenceType")+File.separator+paths.get("path"));
		
		return filePersistence; 
       
    }
    
    public static File getTempOutputMediaFile(int type, String path){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

    	
    	
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                  Environment.DIRECTORY_PICTURES), DIRECTORIO_APP_TEMP + File.separator + path );
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.
        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        
       
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "IMG_"+ timeStamp + ".jpg");
        } else if(type == MEDIA_TYPE_VIDEO) {
            //mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_"+ timeStamp + ".mp4"); 
        	mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_"+ timeStamp + ".mp4"); 
        } else {
            return null;
        }

        return mediaFile;
    }
    
    public static File saveTempToFile(String tempFilePath, long idCelebracion, Context ctx){
    	File fileTemp=new File(tempFilePath);
    	
    	  	
    	
       	File dirApp=ctx.getDir(idCelebracion+"", Context.MODE_WORLD_READABLE);
       	//se crea el directorio de  definitivos
       	File dirSaved=new File(dirApp.toString()+File.separator+DIRECTORIO_APP_SAVED);
       	if(!dirSaved.exists()){
       		dirSaved.mkdir();
       		try {
    			//Se le dan permisos 777 al fichero para que lo pueda ejecutar el videoView ya que usa un componente externo
    			Runtime.getRuntime().exec("chmod 777 "+dirSaved.toString());
    		} catch (IOException e) {
    			
    			e.printStackTrace();
    		}
       	}
       	
       	
    	
    	/* File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                 Environment.DIRECTORY_PICTURES), DIRECTORIO_APP_SAVED + File.separator + path);
    	 if (! mediaStorageDir.exists()){
             if (! mediaStorageDir.mkdirs()){
                 Log.d("MyCameraApp", "failed to create directory");
                 return null;
             }
         }*/
    	 File result=new File(dirSaved.getPath()+File.separator+fileTemp.getName());
    	 try {
 			//Se le dan permisos 777 al fichero para que lo pueda ejecutar el videoView ya que usa un componente externo
 			Runtime.getRuntime().exec("chmod 777 "+result.toString());
 		} catch (IOException e) {
 			
 			e.printStackTrace();
 		}
    	 try{
             FileChannel in = (new FileInputStream(fileTemp)).getChannel();
             FileChannel out = (new FileOutputStream(result)).getChannel();
             in.transferTo(0, fileTemp.length(), out);
             in.close();
             out.close();
             fileTemp.delete();
       }
       catch(Exception e)
       {
          return null;
       }
    	return result;
    }
    public static File[] getAllActiveFile(final int type,long idEventoActivo, Context ctx){
    	 
    	 File raizEvento=ctx.getDir(idEventoActivo+"", Context.MODE_WORLD_READABLE);
    	 File directory = new File(raizEvento.toString()+File.separator+ DIRECTORIO_APP_SAVED );
    	 if(!directory.exists())
    		 return new File[0];
    	 return directory.listFiles(new FilenameFilter(){

			@Override
			public boolean accept(File dir, String filename) {
				if(filename.contains(".3gp") && type==MEDIA_TYPE_VIDEO)
					return true;
				if(filename.contains(".jpg") && type==MEDIA_TYPE_IMAGE)
					return true;
				
				return false;
			}});
    	
    }
    
    public static void copyFolder(File folderOrigen, File folderDestino){
    	 if(!folderDestino.exists() && folderOrigen.isDirectory())
    		 folderDestino.mkdir();
    	 
    	  if (folderOrigen.isDirectory()){
    		  //folderDestino=new File(folderDestino,folderOrigen.getName());
    		  //folderDestino.mkdir();
    		  String[] ficheros = folderOrigen.list();
    		  for (int x=0;x<ficheros.length;x++){
    			  
    			  copyFolder(new File(folderOrigen,ficheros[x]),new File(folderDestino,ficheros[x]));
    		  	}
    	  }else
    			  copiarFicheros(folderOrigen, folderDestino);
    		  
    }
    public static void moveFolderShell(String folderOrigen, String folderDestino){
    	try {
			Runtime.getRuntime().exec(new String[] 
	        		 { "su", "-c","cp -r "+folderOrigen+" "+folderDestino});
			Runtime.getRuntime().exec("rm -r "+folderOrigen);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    public static void copiarFicheros(File fileOrigen, File fileDestino){
    	 
    	  try {
    	    InputStream in = new FileInputStream(fileOrigen);
    	    OutputStream out = new FileOutputStream(fileDestino);
    	 
    	    byte[] buf = new byte[1024];
    	    int len;
    	 
    	    while ((len = in.read(buf)) > 0) {
    	      out.write(buf, 0, len);
    	    }
    	 
    	    in.close();
    	    out.close();
    	 
    	  } catch (IOException ioe){
    	    ioe.printStackTrace();
    	  }
    	}
    
    
    public static void deleteTempFile(String filePath){
    	File f=new File(filePath);
    	f.delete();
    }
}
